package com.qf.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class ParamInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 检查请求头中的必传参数是否都传了
        // 获取必传参数有哪些 ？
        String headkey = "param:product:header";
        Set headParamSet = redisTemplate.opsForSet()
                .members(headkey);

        // 用来存放本次请求中的所有头部参数
        HashSet<String> requestHeaderSet = new HashSet<>();
        // 获取当前请求的所有头部参数
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String head = headerNames.nextElement();
            requestHeaderSet.add(head);
        }

        // 做集合的减法，headParamSet - requestHeaderSet，如果 headParamSet 长度为0 放行，否则说明有必传头部参数没传
        // 抛出异常
        headParamSet.removeAll(requestHeaderSet);
        if (headParamSet.size()!=0){
            log.info("必传头部参数缺少了！"+headParamSet);
            throw new RuntimeException("必传头部参数缺少了！"+headParamSet);
        }


        String querykey = "param:product:query";
        Set queryParamSet = redisTemplate.opsForSet()
                .members(querykey);

        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> reqeustSet = parameterMap.keySet();
        queryParamSet.removeAll(reqeustSet);

        if (queryParamSet.size()>0){
            log.info("必传请求参数缺少了！"+queryParamSet);
            throw new RuntimeException("必传请求参数缺少了！"+queryParamSet);
        }

        return true;

    }
}
